package proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class JDKDynamicProxyDemo {

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        BusinessService targetBusinessService = new BusinessServiceImpl();
        LogAroundInvocationHandler ih = new LogAroundInvocationHandler(targetBusinessService);
        BusinessService businessServiceProxy = (BusinessService) Proxy.newProxyInstance(
                BusinessService.class.getClassLoader(), targetBusinessService.getClass().getInterfaces(), ih);
        // 增强生效
        businessServiceProxy.interfaceMethod2();

        // interfaceMethod1方法内部调用了interfaceMethod2方法，interfaceMethod2方法的增强未生效
        // 因为增强是没有改变委托类，内部还是调用【目标对象】的interfaceMethod2
        businessServiceProxy.interfaceMethod1();

        // 增强生效
        businessServiceProxy.interfaceMethod3();

    }

    public static class LogAroundInvocationHandler implements InvocationHandler {

        private BusinessService target;

        public LogAroundInvocationHandler(BusinessService target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            String methodName = method.getName();
            System.out.println("before method 【" + methodName + "】 invoke");
            Object result;
            try {
                result = method.invoke(target, objects);
            } finally {
                System.out.println("after method 【" + methodName + "】 invoke");
            }
            return result;
        }

    }
}
